package com.stockz.ui.swing.watchlist.widget;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.stockz.core.util.SpringUtil;
import com.stockz.ui.swing.charting.widget.StockChartRightClickPopupMenu;
import com.stockz.ui.swing.widget.JMenu;
import com.stockz.ui.swing.widget.JMenuItem;
import com.stockz.watchlist.manager.WatchListManager;
import com.stockz.watchlist.model.WatchList;

public class AddToWatchListMenu extends JMenu implements AddWatchListToUICallback {
	private static final long serialVersionUID = -92833404485406875L;

	private final Set<WatchList> watchListSet = new HashSet<WatchList>();
	private StockChartRightClickPopupMenu stockChartRightClickPopupMenu;
	private final AddToWatchListActionListener addToWatchListActionListener;
	
	public AddToWatchListMenu(StockChartRightClickPopupMenu parent) {
		super("Add to WatchList");
		this.stockChartRightClickPopupMenu = parent;
		this.addToWatchListActionListener = new AddToWatchListActionListener(this);
		add(new CreateNewWatchListMenuItem(this));
		addSeparator();
		addExistingWatchListsToMenu();
	}
	
	private void addExistingWatchListsToMenu(){
		WatchListManager watchListManager = SpringUtil.getApplicationContext().getBean(WatchListManager.class);
		List<WatchList> watchListList = watchListManager.getAll();
		if(watchListList != null){
			for(WatchList watchList : watchListList){
				addWatchListToUI(watchList);
			}
		}
	}
	
	public void addWatchListToUI(WatchList watchList){
		if(watchListSet.add(watchList)){
			JMenuItem item = new JMenuItem(watchList.getName());
			item.setPayload(watchList);
			item.addActionListener(addToWatchListActionListener);
			add(item);
			addSeparator();
		}
	}

	public StockChartRightClickPopupMenu getStockChartRightClickPopupMenu() {
		return stockChartRightClickPopupMenu;
	}
	
}

